<template>
  <el-row :gutter="20">
    <el-col :span="10">
      <el-form ref="form" label-width="70px">
          <el-form-item label="支付信息">
              <p style="margin:0px">
                  订单总计：现金消费 + 余额消费 + 赠送余额 + 卡耗消费 = {{(fenpeijine.usemoney).toFixed(2)}} + {{(fenpeijine.usebalance).toFixed(2)}} + {{(fenpeijine.usegiftbalance).toFixed(2)}} + {{(fenpeijine.usecard).toFixed(2)}} = {{(fenpeijine.zongji).toFixed(2)}}元
              </p>
              <p style="margin:0px">
                  已支付：卡耗 + 余额 + 赠送余额 = {{(fenpeijine.usecard).toFixed(2)}} + {{(fenpeijine.usebalance).toFixed(2)}} + {{(fenpeijine.usegiftbalance).toFixed(2)}} = {{(fenpeijine.usecard + fenpeijine.usebalance + fenpeijine.usegiftbalance).toFixed(2)}} 元
              </p>
              <p style="margin:0px">
                  应支付：现金支付 = {{fenpeijine.usemoney}} 元
              </p>
          </el-form-item>
          <el-form-item label="跟单人员">
              <template>
                  <el-select v-model="order.gendanid" filterable remote reserve-keyword :remote-method="selectUser" :loading="loading">
                      <el-option :value="0" label="请选择"></el-option>
                      <el-option v-for="item in userlist" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                  </el-select>
              </template>
          </el-form-item>
          <el-form-item label="付款信息">
              <template v-if="order.status == 0">
                  <el-button icon="plus" type="primary" size="small" @click="addRow(payListRef)" class="mb">加一行</el-button>
              </template>
              <el-table :data="paylist" height="300" border>
                  <el-table-column prop="accountname" label="收款账户" :show-overflow-tooltip="showOwer">
                      <template slot-scope="scope">
                          <el-input class="table-line-input" :ref="makeIndex(scope.$index, 1, payListRef)" @focus="setIndex(scope.$index, 1, payListRef)" @blur="blurcheck($event, scope.row.accountname)" @keyup.enter.native="searchAccount($event, scope)" :value="scope.row.accountname" size="small" v-if="order.status == 0">
                              <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupAccount(scope)"></i>
                          </el-input>
                          <span v-else>{{scope.row.accountname}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column prop="type" label="收款方式" width="98">
                      <template slot-scope="scope">
                          <el-tag size="mini" type="success" v-if="scope.row.type == 1">现金支付</el-tag>
                          <el-tag size="mini" type="primary" v-else-if="scope.row.type == 2">可用余额</el-tag>
                          <el-tag size="mini" type="primary" v-else>赠送余额</el-tag>
                      </template>
                  </el-table-column>
                  <el-table-column prop="paymoney" label="收款金额">
                      <template slot-scope="scope">
                          <el-input class="table-line-input" placeholder="元" :ref="makeIndex(scope.$index, 2, payListRef)" @focus="setIndex(scope.$index, 2, payListRef)" v-model="scope.row.paymoney" @keyup.enter.native="nextInput(payListRef)" size="small" v-if="order.status == 0"></el-input>
                          <span v-else>{{scope.row.paymoney}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column prop="" label="操作" width="80" v-if="order.status == 0">
                      <template slot-scope="scope">
                          <el-button type="danger" size="mini" @click="deleterow(scope.$index, paylist)" v-show="scope.row.type == 1">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
              <el-tag type="danger" class="fr" v-if="yingshoujine != 0">应收现金：{{yingshoujine+'元'}}</el-tag>
          </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="14">
        <!-- 现金业绩 -->
        <el-form ref="form" label-width="80px">
            <el-form-item label="业绩提成">
                <el-button icon="plus" type="primary" size="small" @click="addRow(yejiListRef)">加员工</el-button>
                <el-button style="float:right;" type="primary" size="small" icon="upload2" v-if="order.status != 0" @click="chongxinfenpei">重新分配</el-button>
                <el-table :data="yejilist" max-height="250" border>
                    <el-table-column prop="name" label="姓名">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 1, yejiListRef)" @focus="setIndex(scope.$index, 1, yejiListRef)" @blur="blurcheck($event, scope.row.name)" @keyup.enter.native="searchUser($event, scope)" :value="scope.row.name" size="small" :disabled="scope.row.addtype != 1">
                                <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupUser(scope)" v-if="scope.row.addtype === 1"></i>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="xianjinyeji" label="现金业绩">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 2, yejiListRef)" @focus="setIndex(scope.$index, 2, yejiListRef)" v-model="scope.row.xianjinyeji" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="kahaoyeji" label="卡耗业绩">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 3, yejiListRef)" @focus="setIndex(scope.$index, 3, yejiListRef)" v-model="scope.row.kahaoyeji" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="xianjinticheng" label="现金提成">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 4, yejiListRef)" @focus="setIndex(scope.$index, 4, yejiListRef)" v-model="scope.row.xianjinticheng" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="kahaoticheng" label="卡耗提成">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 5, yejiListRef)" @focus="setIndex(scope.$index, 5, yejiListRef)" v-model="scope.row.kahaoticheng" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="xianjinjieti" label="现金阶梯">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 6, yejiListRef)" @focus="setIndex(scope.$index, 6, yejiListRef)" v-model="scope.row.xianjinjieti" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="kahaojieti" label="卡耗阶梯">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 7, yejiListRef)" @focus="setIndex(scope.$index, 7, yejiListRef)" v-model="scope.row.kahaojieti" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="qitaticheng" label="其他提成">
                        <template slot-scope="scope">
                            <el-input class="table-line-input" :ref="makeIndex(scope.$index, 8, yejiListRef)" @focus="setIndex(scope.$index, 8, yejiListRef)" v-model="scope.row.qitaticheng" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="" label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button type="danger" size="mini" @click="deleterow(scope.$index, yejilist)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <el-col :span="24" style="text-align:right">
          <span style="background-color:#f3b5b5;border-radius:3px;color:#fff;padding:3px" v-show="yingfenyeji.yingfenxianjin != 0">现金差：{{yingfenyeji.yingfenxianjin}}元</span>
          <span style="background-color:#f3b5b5;border-radius:3px;color:#fff;padding:3px" v-show="yingfenyeji.yingfenkahao != 0">卡耗差：{{yingfenyeji.yingfenkahao}}元</span>
        </el-col>
    </el-col>
    <div style="position: fixed;bottom: 20px;width: 100%;padding: 0px 20px;box-sizing: border-box;left: 0px;">
        <el-button type="danger" class="fr" style="float: left;" @click="goto(0)">编辑订单</el-button>
        <el-button style="float: left;" @click="dayin" v-qx="quanxian.dayin" v-if="order.status != 0">打印</el-button>
        <el-button icon="check" type="success" style="float: right;" @click="closewin" v-if="order.status == 1">完成</el-button>
        <el-button icon="check" type="success" style="float:right" @click="paysubmit" v-if="order.status == 0" v-qx="quanxian.jiezhang">确定结账</el-button>
        <el-button icon="check" type="warning" style="float:right" @click="fanjiezhang" v-else v-qx="quanxian.fanjiezhang">反结账</el-button>
    </div>
  </el-row>
</template>
<script>
import C from '@/common/common.js'
import S from '@/service/shop/search.js'
import D from '@/service/common/datas.js'
import P from '@/service/shop/popup.js'
import keyUpRef from '@/service/shop/keyupref.js'
import Guest from '@/service/shop/guest.js'
export default {
  name: 'pay',
  props: ['orderprops', 'paylistprops', 'yejilistprops', 'orderlistprops', 'ginfoprops'],
  data () {
    return {
      tichenglist: [],
      loading: true,
      showOwer: true,
      userlist: [],
      payListRef: D.payListRef,
      yejiListRef: D.yejiListRef,
      quanxian: {
        add: 'order_add',
        jiezhang: 'order_jie',
        fanjiezhang: 'order_fan',
        dayin: 'order_print',
        fenpei: 'order_fen',
        fanfenpei: 'order_fanfen',
        chongxinfenpei: 'order_chongxin'
      }
    }
  },
  methods: C.assign(keyUpRef, {
    blurcheck: function (e, value) {
      e.target.value = value
    },
    async selectUser (str) {
      this.loading = true
      let filter = { pagesize: 30, currentpage: 1, keywords: str, ismanage: 1 }
      let userList = await S.searchUser(filter)
      this.loading = false
      this.userlist = userList.list
    },
    async searchAccount (e, scope) {
      if (!C.openLoading()) return false
      let data = await S.searchAccount({ keywords: e.target.value })
      data = data.list.length == 1
        ? data.list[0]
        : await P.accountPopup({ keywords: e.target.value }, data)
      C.closeLoading()

      if (data.id) {
        // 鍒ゆ柇鏄¯鍚﹂噸澶
        let key = C.inarray({ accountid: data.id }, this.paylist)
        if (key == -1) {
          scope.row.accountid = data.id
          scope.row.accountname = data.name
          this.nextInput(this.payListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.payListRef)
        } else {
          C.error('閫夋嫨璐︽埛閲嶅¤嶏紒')
          e.target.select()
          return false
        }
      }
    },
    async firstPopupAccount (scope) {
      this.setIndex(scope.$index, 1, this.payListRef)
      let data = await P.accountPopup({ keywords: '' })
      if (data && data.id) {
        // 判断是否重复
        let key = C.inarray({ accountid: data.id }, this.paylist)
        if (key == -1) {
          scope.row.accountid = data.id
          scope.row.accountname = data.name
          this.nextInput(this.payListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.payListRef)
        } else {
          C.error('选择账户重复！')
          // e.target.select()
          return false
        }
      }
    },
    deleterow: C.deleterow,
    // 结账
    paysubmit: async function () {
      // 判断是否有未分配的业绩和收款金额
      if (this.yingshoujine != 0) {
        C.error('应收现金不正确！')
        return false
      }
      if (this.yingfenyeji.yingfenxianjin != 0 || this.yingfenyeji.yingfenkahao != 0) {
        C.error('分配业绩金额不正确！')
        return false
      }
      let err = false
      let isqian = false
      let initConfig = JSON.parse(C.getLocalStorage('initConfig'))
      this.paylist.forEach((row) => {
        if (!row.accountid || row.accountid <= 0) {
          C.error('收款账户填写不正确！')
          err = true
        }
        if (row.paymoney <= 0) {
          C.error('收款金额填写不正确！')
          err = true
        }
      })

      if (this.yejilist.length) {
        for (var i = 0, xjlen = this.yejilist.length; i < xjlen; i++) {
          if (!this.yejilist[i].userid || this.yejilist[i].userid <= 0) {
            C.error('员工信息填写不正确！')
            return false
          }
          if (!this.yejilist[i].xianjinyeji && !this.yejilist[i].kahaoyeji && !this.yejilist[i].xianjinticheng && !this.yejilist[i].kahaoticheng && !this.yejilist[i].xianjinjieti && !this.yejilist[i].kahaojieti && !this.yejilist[i].qitaticheng) {
            C.error(this.yejilist[i].name + '[员工]分配业绩不正确！')
            return false
          }
        }
      }
      if (this.ginfo.balance - this.fenpeijine.usebalance < 0) isqian = true
      if (this.ginfo.giftbalance - this.fenpeijine.usegiftbalance < 0) {
        C.error('赠送余额不足！')
        return false
      }
      if (err) return false
      if (isqian && !initConfig.isqian) {
        C.error('该客户账户余额不足！')
        return false
      }
      if (isqian && !confirm('该客户余额已不足，会产生欠款，确定要继续吗？')) return false

      // 判断结账时间

      let data = {
        order: this.order,
        paylist: this.paylist,
        yejilist: this.yejilist
      }
      /* console.log(data)
      return false */
      let res = await C.ajax('/shop/order/jiezhang', { data: JSON.stringify(data) }, 'post')
      if (res) {
        C.success(res.data.info)
        this.order.status = 1
        this.goto(2)
      }
    },
    chongxinfenpei: async function () {
      if (this.yingfenyeji.yingfenxianjin != 0 || this.yingfenyeji.yingfenkahao != 0) {
        C.error('分配业绩金额不正确！')
        return false
      }
      if (this.yejilist.length) {
        for (var i = 0, xjlen = this.yejilist.length; i < xjlen; i++) {
          if (!this.yejilist[i].xianjinyeji && !this.yejilist[i].kahaoyeji && !this.yejilist[i].xianjinticheng && !this.yejilist[i].kahaoticheng && !this.yejilist[i].xianjinjieti && !this.yejilist[i].kahaojieti && !this.yejilist[i].qitaticheng) {
            C.error(this.yejilist[i].name + '[员工]分配业绩不正确！')
            return false
          }
        }
      }
      let data = {
        order: this.order, // 订单ID
        yejilist: this.yejilist
      }
      /* console.log(data)
      return false */
      let res = await C.ajax('/shop/order/edityejifenpei', { data: JSON.stringify(data) }, 'post')
      if (res) {
        C.success(res.data.info)
      }
    },
    fanjiezhang: async function () {
      await C.confirm('此操作将清除已结账的信息, 是否继续?', async () => {
        let res = await C.ajax('/shop/order/fanjiezhang', { id: this.order.id }, 'post')
        if (res) {
          C.success(res.data.info)
          // 反结账之后要操作的内容
          this.order.status = 0
          this.goto(1)
        }
      })
    },
    dayin: function () {
      C.openBrowserWindow('/printOpenOrder', { id: this.order.id }, { width: 245, height: 900, useSpa: false, spaModel: 'print' })
    },
    openGuestPage (id) {
      Guest.openGuestPage(id)
    },
    goto (index) {
      this.$emit('goto', {index: index})
    },
    async searchUser (e, scope) {
      if (!C.openLoading()) return false
      let filter = { keywords: e.target.value }
      let data = await S.searchUser(filter)
      data = data.list.length == 1
        ? data.list[0]
        : await P.userPopup(filter, data)
      C.closeLoading()
      if (data && data.id) {
        // 判断是否重复
        let key = C.inarray({ userid: data.id }, this.yejilist)
        if (key == -1) {
          scope.row.userid = data.id
          scope.row.name = data.name
          scope.row.bumenid = data.bumenid
          scope.row.xiaozuid = data.xiaozuid
          this.nextInput(this.yejiListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.yejiListRef)
        } else {
          C.error('选择员工重复！')
          e.target.select()
          return false
        }
      }
    },
    async firstPopupUser (scope) {
      this.setIndex(scope.$index, 1, this.yejiListRef)
      let data = await P.userPopup({ keywords: '' })
      if (data && data.id) {
        // 判断是否重复
        let key = C.inarray({ userid: data.id }, this.yejilist)
        if (key == -1) {
          scope.row.userid = data.id
          scope.row.name = data.name
          scope.row.bumenid = data.bumenid
          scope.row.xiaozuid = data.xiaozuid
          this.nextInput(this.yejiListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.yejiListRef)
        } else {
          C.error('选择员工重复！')
          // e.target.select()
          return false
        }
      }
    },
    closewin: function () {
      C.closeBrowserWindow()
    }
  }),
  computed: {
    shishouxianjin: function () {
      let m = 0
      this.paylist.forEach((row) => {
        m += Number(row.paymoney)
      })
      return m.toFixed(2)
    },
    yingshoujine: function () {
      return Number(this.fenpeijine.usemoney - this.shishouxianjin).toFixed(2)
    },
    fenpeijine: function () {
      let o = { putong: 0, kahao: 0, zancun: 0, zongji: 0, usemoney: 0, usebalance: 0, usegiftbalance: 0, usecard: 0 }
      this.orderlist.forEach((row) => {
        if (row.consumetype == 1) {
          o.putong += Number(row.amount)
        } else if (row.consumetype == 2) {
          o.kahao += Number(row.amount)
        } else {
          o.zancun += Number(row.amount)
        }
        o.zongji += Number(row.amount)

        o.usemoney += Number(row.usemoney)
        o.usebalance += Number(row.usebalance)
        o.usegiftbalance += Number(row.usegiftbalance)
        o.usecard += Number(row.usecard)
      })
      return o
    },
    order () {
      return this.orderprops
    },
    paylist () {
      return this.paylistprops
    },
    yejilist () {
      return this.yejilistprops
    },
    orderlist () {
      return this.orderlistprops
    },
    ginfo () {
      return this.ginfoprops
    },
    yingfenyeji: function () {
      let o = {}
      o.yingfenxianjin = (this.fenpeijine.usemoney - this.shifenyeji.shifenxianjin).toFixed(2)
      o.yingfenkahao = (this.fenpeijine.usecard + this.fenpeijine.usebalance + this.fenpeijine.usegiftbalance - this.shifenyeji.shifenkahao).toFixed(2)
      return o
    },
    shifenyeji: function () {
      let o = { shifenxianjin: 0, shifenkahao: 0 }
      this.yejilist.forEach((row) => {
        o.shifenxianjin += Number(row.xianjinyeji)
        o.shifenkahao += Number(row.kahaoyeji)
      })
      return o
    }
  }
}
</script>